<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <title>商品列表 - 助农购物网站</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<jsp:include page="common/header.jsp"/>

<style>
    .category-sidebar {
        background-color: #f8f9fa;
        border-right: 1px solid #dee2e6;
        padding: 1rem 0;
    }
    .category-sidebar .nav-link {
        color: #495057;
        padding: 0.75rem 1rem;
        border-radius: 0.25rem;
        margin: 0.25rem 0.5rem;
        display: block;
    }
    .category-sidebar .nav-link:hover {
        background-color: #e9ecef;
        color: #212529;
    }
    .category-sidebar .nav-link.active {
        background-color: #0d6efd;
        color: white;
    }
</style>

<div class="container-fluid mt-4">
    <!-- 搜索框 -->
    <div class="row mb-3">
        <div class="col-md-12">
            <form action="${pageContext.request.contextPath}/client/product?action=list" method="get" class="d-flex">
                <input type="text" class="form-control me-2" name="keyword" placeholder="搜索商品..." value="${keyword}">
                <button type="submit" class="btn btn-primary">搜索</button>
            </form>
        </div>
    </div>

    <c:if test="${error != null}">
        <div class="alert alert-danger">${error}</div>
    </c:if>

    <div class="row">
        <!-- 左侧分类栏 -->
        <div class="col-md-3 col-lg-2 category-sidebar">
            <h5 class="mb-3 px-3">商品分类</h5>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link ${category == null || empty category ? 'active' : ''}"
                       href="${pageContext.request.contextPath}/client/index<c:if test='${keyword != null && !empty keyword}'>?keyword=${keyword}</c:if>">
                        全部商品
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link ${category == '蔬菜' ? 'active' : ''}"
                       href="${pageContext.request.contextPath}/client/index?category=蔬菜<c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">
                        蔬菜
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link ${category == '水果' ? 'active' : ''}"
                       href="${pageContext.request.contextPath}/client/index?category=水果<c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">
                        水果
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link ${category == '粮食' ? 'active' : ''}"
                       href="${pageContext.request.contextPath}/client/index?category=粮食<c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">
                        粮食
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link ${category == '禽蛋' ? 'active' : ''}"
                       href="${pageContext.request.contextPath}/client/index?category=禽蛋<c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">
                        禽蛋
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link ${category == '茶叶' ? 'active' : ''}"
                       href="${pageContext.request.contextPath}/client/index?category=茶叶<c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">
                        茶叶
                    </a>
                </li>
            </ul>
        </div>

        <!-- 右侧商品列表 -->
        <div class="col-md-9 col-lg-10">
                    <div class="row">
                        <c:choose>
                            <c:when test="${products != null && !empty products}">
                                <c:forEach var="product" items="${products}">
                                    <div class="col-md-4 mb-4">
                                        <div class="card h-100">
                                            <c:if test="${product.imageUrl != null && !empty product.imageUrl}">
                                                <img src="${product.imageUrl}" class="card-img-top" alt="${product.productName}" style="height: 200px; object-fit: cover; cursor: pointer;"
                                                     onclick="location.href='${pageContext.request.contextPath}/client/product?action=detail&id=${product.productId}'">
                                            </c:if>
                                            <div class="card-body d-flex flex-column">
                                                <h5 class="card-title">${product.productName}</h5>
                                                <p class="card-text text-muted">${product.category}</p>
                                                <p class="card-text text-danger fs-4">¥${product.price}</p>
                                                <div class="mt-auto">
                                                    <a href="${pageContext.request.contextPath}/client/product?action=detail&id=${product.productId}" class="btn btn-primary w-100 mb-2">查看详情</a>
                                                    <c:if test="${sessionScope.user != null}">
                                                        <button type="button" class="btn btn-success w-100" 
                                                                data-product-id="${product.productId}" 
                                                                data-product-name="${product.productName}" 
                                                                data-product-stock="${product.stock}"
                                                                onclick="addToCartFromButton(this)">加入购物车</button>
                                                    </c:if>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </c:forEach>
                            </c:when>
                            <c:otherwise>
                                <div class="col-md-12">
                                    <div class="alert alert-info">
                                        <h5>暂无商品</h5>
                                        <p>商品列表为空，请稍后再试。</p>
                                    </div>
                                </div>
                            </c:otherwise>
                        </c:choose>
                    </div>

                    <!-- 分页 -->
                    <c:if test="${totalPages > 0}">
                        <nav aria-label="Page navigation" class="mt-4">
                            <div class="row">
                                <div class="col-md-12 text-center mb-3">
                                    <span class="text-muted">共 <strong>${totalCount}</strong> 件商品，共 <strong>${totalPages}</strong> 页</span>
                                </div>
                            </div>
                            <ul class="pagination justify-content-center">
                                <li class="page-item ${page == 1 ? 'disabled' : ''}">
                                    <c:choose>
                                        <c:when test="${page == 1}">
                                            <span class="page-link">上一页</span>
                                        </c:when>
                                        <c:otherwise>
                                            <a class="page-link" href="?page=${page-1}<c:if test='${category != null && !empty category}'>&category=${category}</c:if><c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">上一页</a>
                                        </c:otherwise>
                                    </c:choose>
                                </li>
                                <li class="page-item">
                                    <span class="page-link">第 ${page} 页 / 共 ${totalPages} 页</span>
                                </li>
                                <li class="page-item ${hasNextPage == false ? 'disabled' : ''}">
                                    <c:choose>
                                        <c:when test="${hasNextPage == false}">
                                            <span class="page-link">下一页</span>
                                        </c:when>
                                        <c:otherwise>
                                            <a class="page-link" href="?page=${page+1}<c:if test='${category != null && !empty category}'>&category=${category}</c:if><c:if test='${keyword != null && !empty keyword}'>&keyword=${keyword}</c:if>">下一页</a>
                                        </c:otherwise>
                                    </c:choose>
                                </li>
                            </ul>
                        </nav>
                    </c:if>
                </div>
        </div>
    </div>
</div>

<script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
<script>
    // 从按钮获取数据并加入购物车
    function addToCartFromButton(button) {
        const productId = button.getAttribute('data-product-id');
        const productName = button.getAttribute('data-product-name');
        const stock = parseInt(button.getAttribute('data-product-stock'));
        addToCart(productId, productName, stock);
    }
    
    // 加入购物车
    function addToCart(productId, productName, stock) {
        if (stock <= 0) {
            alert('商品已售罄');
            return;
        }

        const quantity = 1; // 列表页默认数量为1

        const params = new URLSearchParams();
        params.append('productId', productId);
        params.append('quantity', quantity);

        fetch('${pageContext.request.contextPath}/client/cart?action=add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            body: params.toString()
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('已添加到购物车');
                    // 更新购物车数量
                    updateCartCount();
                } else {
                    alert(data.message || '添加失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加失败，请重试');
            });
    }

    // 更新购物车数量
    function updateCartCount() {
        fetch('${pageContext.request.contextPath}/client/cart?action=count')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const cartCountEl = document.getElementById('cartCount');
                    if (cartCountEl) {
                        cartCountEl.textContent = data.count;
                        if (data.count > 0) {
                            cartCountEl.style.display = 'inline';
                        } else {
                            cartCountEl.style.display = 'none';
                        }
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
</script>
</body>
</html>

